package org.jinyan.servlet;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.PropertyConfigurator;
import org.jinyan.led.tcp.LedServerSocket;

public class Log4jServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public Log4jServlet() {
	}

	/**
	 * 初始化log4j配置文件的位置，然后重新设置日志文件的记录位置
	 * 
	 * @since 2013-5-27
	 * @throws 如果日志文件初始化失败
	 *             ,那么就抛出运行时异常,不然程序继续运行了. 更正,要考虑容错机制的加入.
	 */
	public void init() throws ServletException {

		/*
		 * try { new ServerSocketFactory().runServer(9080); } catch (IOException
		 * e) { // TODO Auto-generated catch block e.printStackTrace(); }
		 */

		new Thread(new Runnable() {

			@Override
			public void run() {
				LedServerSocket socket = new LedServerSocket();
				while (true) {

					if (socket.isClose()) {
						System.out.println("Socket start");
						socket.restart(11235);
						System.out.println("Socket sucesss");
					}
				}

			}
		}).start();

		String log4jConfigFilePath = this.getServletConfig().getInitParameter(
				"configFile");
		String webRootPath = this.getServletContext().getRealPath("/");
		webRootPath = webRootPath.replaceAll("\\\\", "/");
		System.out.println(webRootPath);
		String log4jConfigFileRealName = webRootPath + log4jConfigFilePath;
		Properties prop = new Properties();
		InputStream is = null;
		try {
			is = new FileInputStream(log4jConfigFileRealName);
			prop.load(is);
			String logFilePath = prop.getProperty("log4j.appender.R.File");
			logFilePath = webRootPath + logFilePath;
			System.out.println(logFilePath);
			PropertyConfigurator.configure(prop);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (is != null) {
					is.close();
				}

			} catch (IOException e1) {
				throw new RuntimeException(e1);
			}
		}

		// WechatToken.getInstance();
	}
}
